package com.mingmen.canting.caigourenyuan;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mingmen.canting.R;
import com.mingmen.canting.activity.LoginActivity;
import com.mingmen.canting.adapter.CaiGouMainAdapter;
import com.mingmen.canting.adapter.ChildAdapter;
import com.mingmen.canting.adapter.MainAdapter;
import com.mingmen.canting.base.BaseBean;
import com.mingmen.canting.defineview.ParentRecyclerView;
import com.mingmen.canting.fragment.BaseFragment;
import com.mingmen.canting.http.callback.StringCallback;
import com.mingmen.canting.httpconfig.HttpResponse;
import com.mingmen.canting.model.GoodsBean;
import com.mingmen.canting.model.MyShopBean;
import com.mingmen.canting.model.NormalBean;
import com.mingmen.canting.model.ShoppingCartModel;
import com.mingmen.canting.util.GsonUtil;
import com.mingmen.canting.util.MyStringUtils;
import com.mingmen.canting.util.SharePreferenceUtil;
import com.mingmen.canting.util.ToolList;
import com.ocnyang.cartlayout.RecyclerViewWithContextMenu;
import com.ocnyang.cartlayout.bean.CartItemBean;
import com.ocnyang.cartlayout.bean.ICartItem;
import com.ocnyang.cartlayout.listener.CartOnCheckChangeListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Response;

@SuppressLint("ValidFragment")
public class DaiCaiGouListfragment extends BaseFragment implements View.OnClickListener {
    private RecyclerView recyclerView;


    private CheckBox mCheckBoxAll;

    private Button mBtnSubmit;

    CaiGouMainAdapter mAdapter;
    String applyDetailId;
    private boolean isEditing;//是否处于编辑状态
    private int totalCount;//购物车商品ChildItem的总数量，店铺条目不计算在内
    private int totalCheckedCount;//勾选的商品总数量，店铺条目不计算在内
    private double totalPrice;//勾选的商品总价格

    String mTitle;
    String token;
    List<ShoppingCartModel.DataBean.SupDataListBean> dataBeanList = new ArrayList<>();
    private int result_fangqi = 200;
    List<String> ids = new ArrayList<>();

    public static DaiCaiGouListfragment getInstance(String title) {
        DaiCaiGouListfragment sf = new DaiCaiGouListfragment();
        sf.mTitle = title;
        return sf;
    }

    List datas = new ArrayList();
    @BindView(R.id.btn_submit)
    Button btn_submit;
    Unbinder unbinder;
    String reason;
    List<String> applyIds = new ArrayList<>();
    List<String> commpanyNames = new ArrayList<>();
    @BindView(R.id.text_time)
    TextView text_time;
    @BindView(R.id.text_total)
    TextView text_total;

    @Override
    public View initView() {
        View v = LayoutInflater.from(getActivity()).inflate(R.layout.fr_daicaigou, null);
        TextView card_title_tv = (TextView) v.findViewById(R.id.card_title_tv);
        recyclerView = ((RecyclerView) v.findViewById(R.id.recycler));
        token = (String) SharePreferenceUtil.get(getActivity(), "token", "");
        unbinder = ButterKnife.bind(this, v);
        mCheckBoxAll = ((CheckBox) v.findViewById(R.id.checkbox_all));

        mBtnSubmit = ((Button) v.findViewById(R.id.btn_go_to_pay));

        mCheckBoxAll.setOnClickListener(this);
        mBtnSubmit.setOnClickListener(this);

        mBtnSubmit.setText(getString(R.string.go_settle_X, 0));


        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        getData();

        // 给列表注册 ContextMenu 事件。
        // 同时如果想让ItemView响应长按弹出菜单，需要在item xml布局中设置 android:longClickable="true"
        registerForContextMenu(recyclerView);
        return v;
    }

    @Override
    public void initData() {

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }

    private int result_shouhuo = 100;

    @OnClick({R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_submit:
//                submitEvent();
                ToolList.removeDuplicateWithOrder(ids);
                String myApplyIds = MyStringUtils.returnStringBuffer(ids);
                Log.d("applyIdsapplyIds", ids.toString());
                Log.d("myApplyIds", myApplyIds);


                String str_send;
                if (flag == 1) {
//                    str_send = "1";
                    str_send = myApplyIds;
                } else {
                    str_send = myApplyIds;
                }
                if (flag == 0) {
                    if (ids.size() == 0) {
                        Toast.makeText(mContext, "请选择商品", Toast.LENGTH_SHORT).show();
                    } else if (ids.isEmpty()) {
                        Toast.makeText(mContext, "请选择商品", Toast.LENGTH_SHORT).show();
                    } else if (cancelFlag.toString().contains("1")) {
                        Toast.makeText(mContext, "请先恢复商品", Toast.LENGTH_SHORT).show();
                    } else {

                        Log.d("str_sendstr_send", str_send);
                        submitData(str_send);
                    }
                } else if (cancelFlag.toString().contains("1")) {
                    Toast.makeText(mContext, "请先恢复商品", Toast.LENGTH_SHORT).show();
                } else {
                    submitData(str_send);
                }


                break;
        }
    }

    public void submitData(String str_send) {
        HttpResponse.createOrder(token, str_send, new StringCallback(getActivity()) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                BaseBean baseBean = new BaseBean();
                baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                if (baseBean.getCode() == 0) {
                    EventBus.getDefault().post(2);

                    commpanyNames.clear();
                    applyIds.clear();
                    ids.clear();
                }

                Toast.makeText(mContext, baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
//                            initData();
                getData();
                Log.d("CAIGOURENYUAN", s);
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    /**
     * 添加选项菜单
     *
     * @param menu
     * @param v
     * @param menuInfo
     */
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        getActivity().getMenuInflater().inflate(R.menu.main_contextmenu, menu);
    }

    /**
     * 选项菜单点击事件
     *
     * @param item
     * @return
     */
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        //获取到的是 listView 里的条目信息
        RecyclerViewWithContextMenu.RecyclerViewContextInfo info = (RecyclerViewWithContextMenu.RecyclerViewContextInfo) item.getMenuInfo();
        Log.d("ContentMenu", "onCreateContextMenu position = " + (info != null ? info.getPosition() : "-1"));
        if (info != null && info.getPosition() != -1) {
            switch (item.getItemId()) {
                case R.id.action_remove:
                    mAdapter.removeChild(info.getPosition());
                    Toast.makeText(getActivity(), "成功移入收藏", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.action_findmore:
                    Toast.makeText(getActivity(), "查找与" + ((GoodsBean) mAdapter.getData().get(info.getPosition())).getGoods_name() + "相似的产品", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.action_delete:
                    mAdapter.removeChild(info.getPosition());
                    break;
                default:
                    break;
            }
        }
        return super.onContextItemSelected(item);
    }

    /**
     * 统计操作<br>
     * 1.先清空全局计数器<br>
     * 2.遍历所有子元素，只要是被选中状态的，就进行相关的计算操作<br>
     * 3.给相关的 textView 进行数据填充
     */
    List<String> receiveList = new ArrayList<>();
    List<String> cancelFlag = new ArrayList<>();

    private void calculate() {
        totalCheckedCount = 0;
        totalCount = 0;
        totalPrice = 0.00;
        receiveList.clear();
        ids.clear();
        applyIds.clear();
        commpanyNames.clear();
        int notChildTotalCount = 0;
        if (mAdapter.getData() != null) {
            for (ICartItem iCartItem : mAdapter.getData()) {
                if (iCartItem.getItemType() == ICartItem.TYPE_CHILD) {
                    totalCount++;

                    if (iCartItem.isChecked()) {
                        totalCheckedCount++;
                        Log.d("totalCheckedCount", totalCheckedCount + "");
//                        totalPrice += ((ShoppingCartModel.DataBean.SupDataListBean.DetailsBean) iCartItem).getGoods_price() * ((GoodsBean) iCartItem).getGoods_amount();
                        receiveList.add(((ShoppingCartModel.DataBean.SupDataListBean.DetailsBean) iCartItem).getCommodityName());

                        ids.add(((ShoppingCartModel.DataBean.SupDataListBean.DetailsBean) iCartItem).getApplyDetailId());
                        ToolList.removeDuplicateWithOrder(ids);
//                        applyIds.add(mList.get(i).getCommodityId());
                        applyIds.add(((ShoppingCartModel.DataBean.SupDataListBean.DetailsBean) iCartItem).getCommodityId());
//                            commpanyNames.add(mList.get(i).getCommodityName());
                        commpanyNames.add(((ShoppingCartModel.DataBean.SupDataListBean.DetailsBean) iCartItem).getCommodityName());
                        ToolList.removeDuplicateWithOrder(applyIds);
                        ToolList.removeDuplicateWithOrder(commpanyNames);
                    }
                } else {

                    notChildTotalCount++;
                }
            }
        } else {
            receiveList.clear();
        }

        mBtnSubmit.setText(getString(isEditing ? R.string.delete_X : R.string.go_settle_X, totalCheckedCount));

        if (mCheckBoxAll.isChecked() && (totalCheckedCount == 0 || (totalCheckedCount + notChildTotalCount) != mAdapter.getData().size())) {
            mCheckBoxAll.setChecked(false);
        }
        if (totalCheckedCount != 0 && (!mCheckBoxAll.isChecked()) && (totalCheckedCount + notChildTotalCount) == mAdapter.getData().size()) {
            mCheckBoxAll.setChecked(true);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //编辑按钮事件

            //提交订单 & 删除选中（编辑状态）
            case R.id.btn_go_to_pay:
                submitEvent();
                break;
            case R.id.checkbox_all:
                mAdapter.checkedAll(((CheckBox) v).isChecked());
                break;
            default:
                break;
        }
    }

    private void submitEvent() {
        if (isEditing) {
            if (totalCheckedCount == 0) {
                Toast.makeText(getActivity(), "请勾选你要删除的商品", Toast.LENGTH_SHORT).show();
            } else {
                mAdapter.removeChecked();
            }

        } else {
            if (totalCheckedCount == 0) {
                Toast.makeText(getActivity(), "你还没有选择任何商品", Toast.LENGTH_SHORT).show();
                receiveList.clear();
            } else {
//                receiveList.add(((GoodsBean) iCartItem).getGoods_name());
                ToolList.removeDuplicateWithOrder(receiveList);
                Log.d("receiveListReceiveList", receiveList.toString());

                Toast.makeText(getActivity(),
                        new StringBuilder().append("你选择了").append(totalCheckedCount).append("件商品")
                                .append("共计 ").append(totalPrice).append("元"),
                        Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 数据初始化尤其重要
     * 1. childItem 数据全部在 GroupItem 数据的下方，数据顺序严格按照对应关系；
     * 2. GroupItem 下的 ChildItem 数据不能为空；
     * 3. 初始化时如果不需要，所有类型的条目都可以不设置ID，GroupItem也不用设置setChilds()；
     * <p>
     * 列表操作时数据动态的变化设置：
     * 1. 通过 CartAdapter 的 addData、setNewData；
     * 2. 单个添加各个条目可以通过对应的 add 方法；
     * 3. 单独添加一个 GroupItem ,可以把它的 ChildItem 数据放到 setChilds 中。
     *
     * @return
     */
    private List<CartItemBean> getData() {
        ArrayList<CartItemBean> cartItemBeans = new ArrayList<>();
        HttpResponse.getShoppingCart(token, "2", "", new StringCallback(getActivity()) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.d("CaiGouRenyuan", s);
                if (dataBeanList.size() > 0) {
                    dataBeanList.clear();
                    cancelFlag.clear();
                }
                BaseBean baseBean = new BaseBean();
                baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                if (baseBean.getCode() == 0) {
                    ShoppingCartModel shoppingCartModel = new ShoppingCartModel();
                    shoppingCartModel = GsonUtil.GsonToBean(s, ShoppingCartModel.class);
                    dataBeanList.addAll(shoppingCartModel.getData().get(0).getSupDataList());
                    List<ShoppingCartModel.DataBean.SupDataListBean.DetailsBean> detailsBeanList = new ArrayList<>();
                    text_time.setText(shoppingCartModel.getData().get(0).getLimitedDate());
                    text_total.setText("总价: " + shoppingCartModel.getData().get(0).getTotal() + "元");
                    for (int i = 0; i < dataBeanList.size(); i++) {
                        ShoppingCartModel.DataBean.SupDataListBean supDataListBean = new ShoppingCartModel.DataBean.SupDataListBean();
                        supDataListBean = dataBeanList.get(i);
                        supDataListBean.setSupplierName(dataBeanList.get(i).getSupplierName());
                        supDataListBean.setItemType(CartItemBean.TYPE_GROUP);
                        cartItemBeans.add(supDataListBean);
                        detailsBeanList = dataBeanList.get(i).getDetails();
                        for (int j = 0; j < detailsBeanList.size(); j++) {
                            ShoppingCartModel.DataBean.SupDataListBean.DetailsBean goodsBean = new ShoppingCartModel.DataBean.SupDataListBean.DetailsBean();
                            goodsBean.setCommodityName(detailsBeanList.get(j).getCommodityName());
                            goodsBean.setItemType(CartItemBean.TYPE_CHILD);
//                            goodsBean.setItemId((j + 1) * 10 + j);
//                            goodsBean.setApplyDetailId(j + 1 + "");
                            goodsBean.setGroupId(i);
//                            commodityId
                            goodsBean.setCommodityId(detailsBeanList.get(j).getCommodityId());
                            goodsBean.setCancelFlag(detailsBeanList.get(j).getCancelFlag());
                            goodsBean.setApplyAmount(detailsBeanList.get(j).getApplyAmount());
                            goodsBean.setPrice(detailsBeanList.get(j).getPrice());
                            goodsBean.setSpecs(detailsBeanList.get(j).getSpecs());
                            goodsBean.setApplyDetailId(detailsBeanList.get(j).getApplyDetailId());
                            goodsBean.setSupplierName(detailsBeanList.get(j).getSupplierName());
                            cancelFlag.add(detailsBeanList.get(j).getCancelFlag());
                            cartItemBeans.add(goodsBean);
                        }
                    }
                    mAdapter = new CaiGouMainAdapter(getActivity(), cartItemBeans, detailsBeanList);
                    mAdapter.setOnCheckChangeListener(new CartOnCheckChangeListener(recyclerView, mAdapter) {
                        @Override
                        public void onCalculateChanged(ICartItem cartItemBean) {
                            calculate();
                        }
                    });
                    mAdapter.setOnitemClickLintener(new CaiGouMainAdapter.ChilditemClick() {
                        @Override
                        public void onItemClick(View view, int position, List<ICartItem> mDatas, String applyDetailId, String cancelFlag) {
                            applyDetailId = applyDetailId;
                            Log.d("applyDetailId", applyDetailId);
                            Log.d("cancelFlag", cancelFlag);
                            if (cancelFlag.equals("1")) {
                                HttpResponse.doShoppingCartCancel(token, applyDetailId, reason, new StringCallback(getActivity()) {
                                    @Override
                                    public void onSuccess(String s, Call call, Response response) {
                                        Log.d("CaiGouRenDaiList", s);
                                        BaseBean baseBean = new BaseBean();
                                        baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                                        Toast.makeText(mContext, baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                                        getData();
                                    }
                                });
                            } else {
                                Intent intent = new Intent(getActivity(), FilterFangQiActivity.class);
                                intent.putExtra("applyDetailId", applyDetailId);
                                startActivityForResult(intent, result_fangqi);
                            }

                        }


                    });
                    mAdapter.setonGroupItemLinstener(new CaiGouMainAdapter.GroupItemClick() {
                        Intent intent;

                        @Override
                        public void onItemClick(View view, int position) {
                            switch (view.getId()) {
                                case R.id.layout_selectshouhuo:
                                    intent = new Intent(getActivity(), ShouhuoListActivity.class);
//                        intent.putExtra("supplierId", mNewList.get(0).getDetails().get(0).getSupplierId());
//                        startActivityForResult(intent, result_shouhuo);

                                    intent.putExtra("supplierId", dataBeanList.get(position).getSupplierId());
//                                    intent.putExtra("supplierId", "0");
                                    startActivity(intent);
                                    break;
                                case R.id.sele_gongYing:
                                    if (TextUtils.isEmpty(ids.toString())) {
                                        Toast.makeText(mContext, "请选择商品", Toast.LENGTH_SHORT).show();
                                    } else if (ids.size() == 0) {
                                        Toast.makeText(mContext, "请选择商品", Toast.LENGTH_SHORT).show();
                                    } else {
                                        String mYdetailIds = MyStringUtils.returnStringBuffer(ids);
                                        String applyId_s = MyStringUtils.returnStringBuffer(applyIds);
                                        String commpanyName_s = MyStringUtils.returnStringBuffer(commpanyNames);
                                        intent = new Intent(getActivity(), SelectGongYingActivity.class);
                                        intent.putExtra("detailIds", mYdetailIds);
                                        intent.putExtra("position", position + "");
                                        intent.putExtra("applyId_s", applyId_s);
                                        intent.putExtra("commpanyNames", commpanyName_s);
                                        startActivityForResult(intent, result_shouhuo);
                                    }

                                    break;
                            }

                        }
                    });
                    recyclerView.setAdapter(mAdapter);
                } else if (baseBean.getCode() == 401) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                    getActivity().finish();
                } else {
                    Toast.makeText(getActivity(), baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                }

            }
        });

        return cartItemBeans;
    }

    String resurtResurant;

    int flag = 0;
    String gongName;
    String position;
    String receivestr;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == result_shouhuo) {
            resurtResurant = data.getStringExtra("flag");
            gongName = data.getStringExtra("gongName");
            position = data.getStringExtra("position");
            Log.d("resurtResurantFlag", resurtResurant);

            Log.d("gongNamegongName", gongName);
            if (resurtResurant.equals("1")) {
                flag = 1;
//                receivestr = data.getStringExtra("idSend_receiver");
//                Log.d("receivestr", receivestr);
            } else {
//
                flag = 0;
            }
            if (dataBeanList.size() > 0) {
                dataBeanList.clear();
            } else {
            }
   /*         String mYdetailIds = MyStringUtils.returnStringBuffer(ids);
            String applyId_s = MyStringUtils.returnStringBuffer(applyIds);
            String commpanyName_s = MyStringUtils.returnStringBuffer(commpanyNames);*/
            commpanyNames.clear();
            applyIds.clear();
            getData();

        } else if (resultCode == result_fangqi) {
            reason = data.getStringExtra("reason");
            Log.d("Caiagdouddkdk", reason);
            String applyDetailId = data.getStringExtra("applyDetailId");
            HttpResponse.doShoppingCartCancel(token, applyDetailId, reason, new StringCallback(getActivity()) {
                @Override
                public void onSuccess(String s, Call call, Response response) {
                    Log.d("CaiGouRenDaiList", s);
                    BaseBean baseBean = new BaseBean();
                    baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                    Toast.makeText(mContext, baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                    if (dataBeanList.size() > 0) {
                        dataBeanList.clear();
                    } else {
                    }
                    getData();
                }
            });

        }
    }
}